<?php

namespace common\models\goods;

use Yii;
use common\models\AR;

/**
 * This is the model class for table "{{%goods_category}}".
 *
 * @property integer $id
 * @property string $name
 * @property integer $parent_id
 * @property integer $sort
 */
class GoodsCategory extends AR {

    public $modelName = '商品类目';
    private $cacheRouteKey = 'goodsCategory_route';

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%goods_category}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['name'], 'required'],
            [['parent_id', 'sort'], 'integer'],
            ['sort', 'default', 'value' => 0],
            [['name'], 'string', 'max' => 45],
            [['brand_ids'], 'string', 'max' => 200],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '类目名称',
            'parent_id' => '父ID',
            'sort' => '排序',
            'brand_ids' => '关联品牌',
        ];
    }

    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);
        Yii::$app->cache->delete($this->cacheRouteKey);
    }

    /**
     * 获取子节点数
     * @return integer 子节点数
     */
    public function getChildCount() {
        return $this->find()->where(['parent_id' => $this->id])->count();
    }

    /**
     * 获取从根节点到当前节点的ID路径
     * @param type $id 当前节点ID
     * @param type $ids 
     * @return [GoodsCategory] 从根节点到当前节点商品类目集合
     * @throws \yii\web\HttpException
     */
    public function getRoute($id = null, $ids = []) {
        $route = Yii::$app->cache->get($this->cacheRouteKey);
        $route === false && $route = [];

        if (is_null($id)) {
            if (isset($route[$this->id])) {
                return $route[$this->id];
            }

            $id = $this->parent_id;
        }

        if ($id == 0) {
            $route[$this->id] = $ids;
            Yii::$app->cache->set($this->cacheRouteKey, $route);

            return $ids;
        }
        $node = $this->findOne(['id' => $id]);
        if ($node) {
            array_unshift($ids, $node);
            return $this->getRoute($node->parent_id, $ids);
        } else {
            throw new \yii\web\HttpException('获取商品类目路径错误！');
        }
    }

    /**
     * 根据ID，获取该ID下的所有子类目
     * @param integer $pid 父ID，默认为0
     * @return array GoodsCategory
     */
    public static function getList($pid = 0) {
        return self::find()->where(['parent_id' => $pid])->all();
    }

}
